<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部自定义工具栏 -->
      <page-tools>
        <!-- 左侧 -->
        <template #slot-left>
          <span>共 {{ total }} 条记录</span>
        </template>
        <!-- 右侧 -->
        <template #slot-right>
          <el-button
            v-power="'import'"
            type="danger"
            size="small"
            @click="$router.push('/excel')"
          >导入excel</el-button>
          <el-button
            v-power="'export'"
            type="success"
            size="small"
            @click="downloadExcel"
          >导出excel</el-button>
          <el-button
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <!-- 卡片 -->
      <el-card class="box-card">
        <el-table
          :data="employeesList"
          style="width: 100%"
          border
          :default-sort="{ prop: 'workNumber', order: 'ascending' }"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column
            prop="formOfEmployment"
            :formatter="formatterFn"
            label="聘用形式"
          />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.timeOfEntry | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="correctionTime" label="转正时间" sortable>
            <template v-slot="scope">
              <span>{{ scope.row.correctionTime | formatTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmpFn(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[10, 15, 20, 25]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 弹框 -->
        <el-dialog
          title="新增员工"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="showDialog"
          width="50%"
          center
          @close="closeDialog"
        >
          <emp-dialog
            ref="addEmpt"
            @close="showDialog = false"
            @updateList="updateListFn"
          />
        </el-dialog>
        <!-- 分配角色弹框 -->
        <el-dialog
          title="分配角色"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="showRoleDialog"
          width="50%"
          center
        >
          <assign-role v-if="showRoleDialog" :parent-id="parentId" @close="closeRoleDialog" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
// import { PageTools } from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
// 引入枚举数据
import EmployeeEnum from '@/constant/employees'
// 引入组件
import EmpDialog from './empDialog.vue'
import AssignRole from './assignRole'
//  格式化时间
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    // PageTools
    EmpDialog,
    AssignRole
  },
  filters: {
    // 格式化时间
    formatTime(time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 10 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false, // 新增员工弹框的展示与隐藏
      showRoleDialog: false, // 分配角色弹框展示与隐藏
      parentId: '' // 用户id
    }
  },
  created() {
    // 调用获取员工列表
    this.getEmployeeList()
  },
  methods: {
    // 关闭新增角色弹框
    closeRoleDialog() {
      this.showRoleDialog = false
    },
    // 分配角色
    setEmp(id) {
      this.showRoleDialog = true
      this.parentId = id
    },
    // 格式化后端返回的数据,满足xlsx插件要求
    transData(rows) {
      const map = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 格式化表头
      const headerKeys = Object.keys(rows[0])
      // 拿到中文表头
      const header = headerKeys.map(item => {
        return map[item]
      })
      // 格式化内容
      const data = rows.map(obj => {
        return Object.values(obj)
      })
      return { header, data }
    },
    // 导出excel
    async downloadExcel() {
      const res = await getEmployeeList(this.query)
      const excelObj = this.transData(res.data.rows)

      // 模拟数据
      // const header = ['序号', '姓名']
      // const data = [
      //   ['1', '刘备'],
      //   ['2', '关羽']
      // ]

      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: '员工信息列表', // 导出文件名
          autoWidth: true, // 单元格自适应
          bookType: 'xlsx' // 文件类型
        })
      })
    },
    // 监听添加员工关闭
    closeDialog() {
      // 获取子组件实例
      this.$refs.addEmpt.resetForm()
    },

    // 刷新列表和关闭弹框
    updateListFn() {
      this.getEmployeeList()
      this.showDialog = false
    },

    // 格式化聘用形式
    formatterFn(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(
        (item) => item.id === Number(cellValue)
      )
      return obj ? obj.value : '未知'
    },

    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    // 点击删除员工
    async delEmpFn(id) {
      const confirmRes = await this.$confirm(
        '此操作将删除该员工信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 点击取消
      if (confirmRes === 'cancel') return this.$message('取消删除')
      // 点击确定
      const res = await delEmployee(id)
      // 当前页数据只有一条,点击删除后,,让页码减1
      if (this.employeesList.length === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          // :如果第一页只剩一条数据，删除以后，让:page:还原为1
          this.query.page = 1
        }
      }
      // 提示
      this.$message.success(res.message)
      // 刷新列表
      this.getEmployeeList()
    },

    // 每页显示条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeeList()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeeList()
    }
  }
}
</script>

<style lang="scss" scoped>
.staffPhoto {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
.box-card {
  margin-top: 20px;
}
.el-pagination {
  text-align: center;
  margin-top: 10px;
}
</style>
